package com.sukumar.android.sms.service;

import java.io.IOException;

import com.sukumar.android.sms.R;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;

public class SmsNotifierService extends Service {
	MediaPlayer mMediaPlayer;
	Vibrator mVibrator;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		playNotification(getApplicationContext());
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mMediaPlayer.stop();
		mVibrator.cancel();
	}

	private void playNotification(Context pContext) {
		mMediaPlayer = new MediaPlayer();
		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(pContext);

		try {
			String prefRingtone = myPrefs.getString(getText(R.string.ringtoneKey).toString(), "");
			Uri ringtoneUri = Uri.parse(prefRingtone);

			mMediaPlayer.setDataSource(pContext, ringtoneUri);

			final AudioManager audioManager = (AudioManager) pContext
					.getSystemService(Context.AUDIO_SERVICE);
			int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.ADJUST_RAISE);

			if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mMediaPlayer.setLooping(true);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		boolean prefVibration = myPrefs.getBoolean(getText(R.string.enable_vibrator_key).toString(),true);
		if(prefVibration){
			long[] pattern = { 0, 300, 200 };
			mVibrator.vibrate(pattern, 0);
		}		
	}

}
